package com.lzh.persevere.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lzh.persevere.common.R;
import com.lzh.persevere.common.ResultUtil;
import com.lzh.persevere.model.entity.GuestBook;
import com.lzh.persevere.model.qo.ModuleIdQO;
import com.lzh.persevere.model.ro.guestbook.AddGuestbookRO;
import com.lzh.persevere.model.vo.guestbook.GuestBookVO;
import com.lzh.persevere.service.GuestBookService;
import com.lzh.persevere.service.impl.RedisCacheService;
import com.lzh.persevere.utils.IpUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 弹幕controller
 *
 * @author luzhiheng
 * @since 2025-07-06
 */
@RestController
@RequestMapping("/guestbook")
public class GuestBookController {

    @Resource
    private GuestBookService guestBookService;

    @Resource
    private RedisCacheService redisCacheService;

    @ApiOperation(value = "查询弹幕列表")
    @PostMapping("/findGuestbookList")
    public R<List<GuestBookVO>> findGuestbookList(@Valid @RequestBody ModuleIdQO qo) {
        List<GuestBook> guestBookList = guestBookService.list(
                Wrappers.<GuestBook>lambdaQuery().eq(GuestBook::getModuleId, qo.getModuleId())
        );
        List<GuestBookVO> guestBookVOList = BeanUtil.copyToList(guestBookList, GuestBookVO.class);
        if (CollectionUtil.isNotEmpty(guestBookList)) {
            Map<String, String> userIdAvatarMap = redisCacheService.getAllUserIdAvatarMap();
            guestBookVOList.forEach(e -> {
                e.setAvatar(userIdAvatarMap.get(e.getCreateUserId()));
            });
        }
        return ResultUtil.success(guestBookVOList);
    }

    @ApiOperation(value = "添加弹幕")
    @PostMapping("/addGuestbook")
    public R<Boolean> addGuestbook(@Valid @RequestBody AddGuestbookRO ro) {
        GuestBook guestBook = new GuestBook()
                .setIp(IpUtil.getIpAddress())
                .setModuleId(ro.getModuleId())
                .setContent(ro.getContent());
        return ResultUtil.success(guestBookService.save(guestBook));
    }
}
